from django.shortcuts import render, HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from .ser import *
from utils.comm import send_message, get_redis
from day00 import settings
import jwt
# Create your views here.


import redis
from django.contrib.auth.hashers import make_password, check_password


# class Text(APIView):
#     def get(self,request):
#         # result = send_message('15947159146','521314',1)
#         # print(result)
#         # return Response('ok')
#         conn = get_redis()
#         # conn.setex('username',60,'cheng')
#         name = conn.get('username')
#         return Response(name)


class Newsmanage(APIView):
    def post(self, request):
        ser = Newsser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        sr = News.objects.all()
        p = Paginator(sr, 2)
        cpage = request.GET.get('p')
        rel = p.page(cpage)
        ser = Newsser(rel, many=True)
        return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})


from django.core.paginator import Paginator


class Admanage(APIView):
    def post(self, request):
        ser = Adser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        sr = Ad.objects.all()
        p = Paginator(sr, 2)
        cpage = request.GET.get('p')
        rel = p.page(cpage)
        ser = Adser(rel, many=True)
        return Response({'code': 200, 'list': ser.data, 'tpage': p.num_pages})


import re


class Register(APIView):
    def post(self, request):
        # 用户名
        username = request.data.get('username')
        if not username:
            return Response({'code': 10010})
        reg = re.match('\w{5,10}$', username)
        if not reg:
            return Response({'code': 10011})
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 10012})

        # 验证密码
        password = request.data.get("password")
        if not password:
            return Response({"code": 10016})
        sreg = re.match("\w{5,20}$", password)
        if not sreg:
            return Response({"code": 10017})
        # return Response({"code": 200})

        # 验证确认密码
        password1 = request.data.get("password1")
        if not password1:
            return Response({"code": 10020})
        msg = re.match("\w{5,20}$", password1)
        if not msg:
            return Response({"code": 10021})
        if password != password1:
            return Response({"code": 20022})

        # 手机号
        mobile = request.data.get('mobile')
        if not mobile:
            return Response({'code': 10013})
        mreg = re.match('^1[3-9]\d{9}$', mobile)
        if not mreg:
            return Response({'code': 10014})
        mob = User.objects.filter(mobile=mobile).first()
        if mob:
            return Response({'code': 10015})

            # 验证码验证newcode,redis取,根据手机号
        smscode = request.data.get('smscode')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code, encoding='utf8')
        if smscode != code:
            return Response({"code": 10016})

        # 判断是否同意协议
        agree = request.data.get('agree')
        if not agree:
            return Response({"code": 10031})

        # 注册
        request.data['password'] = make_password(request.data.get('password'))
        ser = Userser(data=request.data)
        if ser.is_valid():
            ser.save()

            token = jwt.encode({'data': {'username': username}},
                               settings.SECRET_KEY, algorithm='HS256')
            # pyjwt生成token返回
            return Response({"code": 200, 'token': token, 'userid': ser})
        else:
            return Response({"code": 10017})


# # 发送短信验证码
import random


class SendMes(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        uid = request.data.get('uid')
        imgcode = str(request.data.get('imgcode'))

        # print(uid)
        print(imgcode)
        conn = get_redis()
        image = conn.get(uid)
        # print(image)
        if image:
            image = str(image, encoding='utf8')
            if image.lower() == imgcode.lower():
                codesms = random.randint(100000, 999999)
                res = send_message(mobile, str(codesms), 1)
                code = 10010
                if res:
                    code = 200
                    # 发送验证码成功后存入redis
                    conn.setex(mobile, 60, codesms)
                return Response({'code': code})
            return Response({'code': 10023})
        return Response({'code': 10022})


# 生成图片验证码
from utils.captcha.captcha import captcha
from utils import comm


class Createcaptcha(APIView):
    def get(self, request):
        # 获取uuid
        uuid = request.GET.get('uuid')
        # 生成图片验证码
        name, text, img = captcha.generate_captcha()
        # 获取redis连接
        redis_con = comm.get_redis()
        # 图片验证码存储在redis里面
        redis_con.set(uuid, text)
        # 以图片方式输出
        return HttpResponse(img, content_type='image/jpg')


from django.db.models import Q


class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(Q(username=username) | Q(mobile=username)).first()
        if user:
            if check_password(user.password, password):
                token = jwt.encode({'data': {'username': username, id: user.id}},
                                   settings.SECRET_KEY, algorithm='HS256')
                return Response({'code': 200, 'token': token, 'userid': user.id})
        return Response({'code': 20010})


class Address(APIView):
    def post(self, request):
        ser = Addressser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self, request):
        se = Address.objects.all()
        ser = Addressser(se, many=True)


class AreaM(APIView):
    def get(self, request):
        pid = request.GET.get('pid')
        if not pid:
            # 获取省
            areas = Area.objects.filter(parent_id__isnull=True).all()
        else:
            # 获取市或者区
            areas = Area.objects.filter(parent_id=pid).all()

        ser = AreaSer(areas, many=True)
        return Response({"code": 200, 'list': ser.data})